<?php
/**
 * 职位
 * 
 * 
 * 
 * @property integer $id
 * @property integer $deptid
 * @property string $parentid
 * @property string $name
 * @property string $cid
 * @property string $dutyid
 * @property string $description
 * @property string $state
 * @property string $createtime
 * @property string $updatetime
 * 
 * 
 */
class Position extends CDbActiveRecord {
	/**
	 * 缓存方式载入职位数据
	 *
	 * @return array $data 返回职位数据
	 */
	public function loadData() {
		// Yii::app ()->memcache->delete ( get_class ( $this ) );
		$cachekey = get_class ( $this );
		if (false === ($data = Yii::app ()->memcache->get ( $cachekey ))) {
			$data = self::model ()->published ()->findAll ( array (
					'limit' => 5 
			) );
			Yii::app ()->memcache->set ( $cachekey, $data, 3600 * 24 );
		}
		// print_r ( $cacheData );
		return $data;
	}
	/**
	 * 删除职位缓存
	 */
	public function deleteCache() {
		Yii::app ()->memcache->delete ( get_class ( $this ) ); // deleteValue
	}
	public function __set($name, $value) {
		echo "<BR>$name, $value";
	}
	public function __get($name) {
		echo "<BR>get$name";
		$getter = 'get' . $name;
		if (method_exists ( $this, $getter ))
			return $this->$getter ();
	}
	public function __isset($name) {
		$getter = 'get' . $name;
		if (method_exists ( $this, $getter ))
			return $this->$getter () !== null;
	}
	public function defaultScope() {
		return array (
				'condition' => "state=1" 
		);
	}
	public function scopes() {
		return array (
				'published' => array (
						'condition' => 'state=1' 
				) 
		);
	}
	/**
	 * 获取职位信息
	 *
	 * @param string $positionId        	
	 */
	public static function getPosition($positionId = '') {
		$data = self::findAllPosition ();
		return isset ( $data [$positionId] ) ? $data [$positionId] : false;
	}
	/**
	 * 将数组创建成树的结构数组
	 *
	 * @param array $elements
	 *        	数组
	 * @param int $parentId
	 *        	父id
	 * @param int $depth
	 *        	节点的层级
	 * @return array $branch 生成树的结构数组
	 */
	public static function buildTree(array $elements, $parentId = 0, $depth = 1) {
		$branch = array ();
		foreach ( $elements as $element ) {
			if ($element ['parentid'] == $parentId) {
				$element ['depth'] = $depth;
				// $element ['open'] = 'true';
				$children = self::buildTree ( $elements, $element ['id'], $depth + 1 );
				if ($children) {
					$element ['children'] = $children;
				}
				$branch [] = $element;
			}
		}
		return $branch;
	}
	/**
	 * 获取所以职位信息
	 *
	 * @author Poly
	 */
	public static function findAllPosition() {
		$cacheName = Yii::app ()->params ['cache'] ['System_Position'];
		$cacheKey = $cacheName [0];
		$cacheTime = $cacheName [1];
		// Yii::app ()->cache->delete ( $cacheKey );
		$cache = Yii::app ()->cache->get ( $cacheKey );
		
		// 缓存返回
		if ($cache !== false) {
			return $cache;
		}
		$tn = Position::tableName ();
		$sql = "SELECT id,deptid,parentid,name,cid,dutyid,description,state FROM `$tn` ORDER BY id ASC";
		$result = Yii::app ()->db->createCommand ( $sql )->queryAll ();
		$positions = array ();
		if ($result) {
			foreach ( $result as $k => $v ) {
				$positions [$v ['id']] = $v;
			}
		}
		Yii::app ()->cache->set ( $cacheKey, $positions, $cacheTime );
		return $positions;
	}
	/**
	 * 清除职位缓存
	 *
	 * @author Poly
	 */
	public static function cCache() {
		// 清理缓存
		$cacheName = Yii::app ()->params ['cache'] ['System_Position'];
		$cacheKey = $cacheName [0];
		Yii::app ()->cache->delete ( $cacheKey );
	}
	protected function afterSave() {
		self::cCache ();
		return parent::afterSave ();
	}
	protected function afterDelete() {
		self::cCache ();
		return parent::afterDelete ();
	}
	public static function model($className = __CLASS__) {
		return parent::model ( $className );
	}
	public function tableName() {
		return '{{position}}';
	}
	public function rules() {
		return array (
				array (
						'deptid, name',
						'required' 
				),
				array (
						'deptid',
						'numerical',
						'integerOnly' => true 
				),
				array (
						'name',
						'length',
						'max' => 20 
				),
				
				array (
						'id, deptid, name',
						'safe',
						'on' => 'search' 
				) 
		);
	}
	public function relations() {
		return array ();
	}
	public function attributeLabels() {
		return array (
				'id' => 'ID',
				'deptid' => 'Deptid',
				'name' => 'Name' 
		);
	}
	public function search() {
		$criteria = new CDbCriteria ();
		
		$criteria->compare ( 'id', $this->id );
		$criteria->compare ( 'deptid', $this->deptid );
		$criteria->compare ( 'name', $this->name, true );
		
		return new CActiveDataProvider ( get_class ( $this ), array (
				'criteria' => $criteria 
		) );
	}
	
	/**
	 * @autor Poly
	 *
	 * @return array 返回对应部门所有职位 id=>name
	 */
	public static function getDeptidPosition($deptid) {
		$deptid = intval ( $deptid );
		$data = self::findAllPosition ();
		$arr = array ();
		foreach ( $data as $k => $v ) {
			if ($v ['deptid'] == $deptid)
				$arr [$v ['id']] = $v ['name'];
		}
		return $arr;
	}
	/**
	 * 获取所有下级职位的用户ID
	 *
	 * @param int $posId
	 *        	职位ID
	 * @param array $data
	 *        	职位数据
	 * @return boolean array 的所有下级职位
	 */
	public static function subordinatePositionUid($posId) {
		$cacheName = Yii::app ()->params ['cache'] ['System_SubordinatePositionUid'];
		
		$cacheTime = $cacheName [1];
		$cacheKey = md5 ( str_replace ( '{condition}', $posId, $cacheName [0] ) );
		
		$cache = Yii::app ()->cache->get ( $cacheKey );
		if ($cache !== false) {
			Yii::trace ( "从缓存获取所有" . $posId . "下级职位的用户ID", 'Position' );
			return $cache;
		}
		Yii::trace ( "获取所有" . $posId . "下级职位的用户ID", 'Position' );
		
		$ordinte = self::subordinatePosition ( $posId );
		if ($ordinte == array ()) {
			return false;
		}
		$ordinteIds = array ();
		foreach ( $ordinte as $k => $v ) {
			$ordinteIds [] = $v ['id'];
		}
		$ids = implode ( ',', $ordinteIds );
		$tn = Users::tableName ();
		
		$sql = "SELECT uid FROM $tn WHERE positionid IN($ids)";
		
		$result = Yii::app ()->db->createCommand ( $sql )->queryAll ();
		$uids = array ();
		if ($result) {
			foreach ( $result as $k => $v ) {
				$uids [] = $v ['uid'];
			}
		}
		Yii::app ()->cache->set ( $cacheKey, $uids, $cacheName [1] );
		return $uids;
	}
	
	/**
	 * 获取所有下级职位的用户
	 *
	 * @param int $posId
	 *        	职位ID
	 * @param array $data
	 *        	职位数据
	 * @return boolean array 的所有下级职位
	 */
	public static function subordinatePositionUser($posId) {
		$cacheName = Yii::app ()->params ['cache'] ['System_SubordinatePositionUser'];
		
		$cacheTime = $cacheName [1];
		$cacheKey = md5 ( str_replace ( '{condition}', $posId, $cacheName [0] ) );
		
		$cache = Yii::app ()->cache->get ( $cacheKey );
		if ($cache !== false) {
			Yii::trace ( "从缓存获取所有" . $posId . "下级职位的用户", 'Position' );
			return $cache;
		}
		Yii::trace ( "获取所有" . $posId . "下级职位的用户", 'Position' );
		
		$ordinte = self::subordinatePosition ( $posId );
		if ($ordinte == array ()) {
			return false;
		}
		$ordinteIds = array ();
		foreach ( $ordinte as $k => $v ) {
			$ordinteIds [] = $v ['id'];
		}
		$ids = implode ( ',', $ordinteIds );
		$tn = Users::tableName ();
		
		$sql = "SELECT uid,username,name,ename,deptid,positionid,cid FROM $tn WHERE positionid IN($ids)";
		
		$result = Yii::app ()->db->createCommand ( $sql )->queryAll ();
		
		Yii::app ()->cache->set ( $cacheKey, $result, $cacheName [1] );
		return $result;
	}
	/**
	 * 获取所有下级职位
	 *
	 * @param int $posId
	 *        	职位ID
	 * @param array $data
	 *        	职位数据
	 * @return boolean array 的所有下级职位
	 */
	public static function subordinatePosition($posId) {
		$cacheName = Yii::app ()->params ['cache'] ['System_SubordinatePosition'];
		
		$cacheTime = $cacheName [1];
		$cacheKey = md5 ( str_replace ( '{condition}', $posId, $cacheName [0] ) );
		
		$cache = Yii::app ()->cache->get ( $cacheKey );
		if ($cache !== false) {
			Yii::trace ( "从缓存获取所有下级职位", 'Position' );
			return $cache;
		}
		Yii::trace ( "获取所有下级职位", 'Position' );
		$data = self::findAllPosition ();
		if (! $data)
			return array ();
		$result = self::findSubordinate ( $posId, $data );
		
		Yii::app ()->cache->set ( $cacheKey, $result, $cacheName [1] );
		return $result;
	}
	
	/**
	 * 获取所有上级职位
	 *
	 * @param int $posId
	 *        	职位ID
	 * @param array $data
	 *        	职位数据
	 * @return boolean array 的所有上级职位
	 */
	public static function higherPosition($posId) {
		$cacheName = Yii::app ()->params ['cache'] ['System_HigerPosition'];
		$cacheTime = $cacheName [1];
		$cacheKey = md5 ( str_replace ( '{condition}', $posId, $cacheName [0] ) );
		$cache = Yii::app ()->cache->get ( $cacheKey );
		if ($cache !== false) {
			Yii::trace ( "从缓存获取所有上级职位", 'Position' );
			return $cache;
		}
		Yii::trace ( "获取所有上级职位", 'Position' );
		$data = self::findAllPosition ();
		if (! $data)
			return array ();
		
		$result = self::findHigher ( $posId, $data );
		
		Yii::app ()->cache->set ( $cacheKey, $result, $cacheName [1] );
		return $result;
	}
	/**
	 * 找出下属职位
	 *
	 * @author Eddie
	 * @param int $posId
	 *        	所在职位ID
	 * @param array $data
	 *        	职位数据
	 * @return array
	 */
	public static function findSubordinate($posId, $data) {
		static $i = 0, $ordinate = array ();
		if (! $data)
			return array ();
		foreach ( $data as $k => $v ) {
			if ($v ['parentid'] == $posId) {
				$ordinate [] = $v;
				unset ( $data [$k] );
				self::findSubordinate ( $v ['id'], $data );
			}
		}
		
		return $ordinate;
	}
	
	/**
	 * 获取所有上级职位
	 *
	 * @param int $posId
	 *        	职位ID
	 * @param array $data
	 *        	职位数据
	 * @return boolean array 的所有上级职位
	 */
	public static function findHigher($posId, $data) {
		static $arr = array ();
		
		if (! $data)
			return false;
		
		foreach ( $data as $k => $v ) {
			if ($v ['id'] == $posId) {
				$arr [] = $v ['id'];
				if ($v ['parentid'] != 0) {
					$tmp = $v;
					unset ( $data [$k] );
					self::findHigher ( $tmp ['parentid'], $data );
				}
			}
		}
		return $arr;
	}
	
	/**
	 * 根据职位ID找出下属员工
	 *
	 * @param int $posId
	 *        	职位ID
	 * @return array id=>value
	 */
	public static function getSubordinateByPostionId($posId) {
		// 找出下属员工信息
		$subPosUsers = self::subordinatePositionUser ( $posId );
		$subUser = array (
				'' => '全部' 
		);
		if (! $subPosUsers)
			return $subUser;
		foreach ( $subPosUsers as $k => $v ) {
			$subUser [$v ['uid']] = $v ['name'];
		}
		return $subUser;
	}
	//其他代码
	
	public function beforeSave()
	{
		parent::beforeSave();
		//自己的行为事件
	}
}
